﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Qiniu.Http;
using Qiniu.Storage;
using Qiniu.Util;
using QiniuOSS.Web.Models;

namespace QiniuOSS.Web.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly QnySetting _Qny;

        public HomeController(ILogger<HomeController> logger, IOptions<QnySetting> Qny)
        {
            _logger = logger;
            _Qny = Qny.Value;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Upload()
        {
            return View();
        }

        //public IActionResult UploadToQiniu()
        //{
        //    var mac = new Mac(_Qny.qiniuyunAK, _Qny.qiniuyunSK);

        //    var putPolicy = new PutPolicy
        //    {
        //        Scope = _Qny.qiniuyunBucket
        //    };
        //    putPolicy.SetExpires(3600);

        //    var uploadToken = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());

        //    var config = new Config()
        //    {
        //        Zone = Zone.ZONE_CN_East,
        //        UseHttps = true
        //    };
        //    var uploadManager = new UploadManager(config);

        //    var files = Request.Form.Files;
        //    foreach (IFormFile file in files)//获取多个文件列表集合
        //    {
        //        if (file.Length > 0)
        //        {
        //            var fileName = file.FileName.Substring(file.FileName.LastIndexOf('.')); //文件扩展名
        //            var saveKey = _Qny.prefixPath + "/" + Guid.NewGuid().ToString("N") + fileName;//重命名文件加上时间戳

        //            var stream = file.OpenReadStream();
        //            var result = uploadManager.UploadStream(stream, saveKey, uploadToken, null);

        //            if (result.Code == 200)
        //            {
        //                return Json(result.Text);
        //            }
        //            else
        //            {
        //                throw new Exception(result.RefText);//上传失败错误信息
        //            }
        //        }
        //    }

        //    return null;
        //}

        [HttpPost]
        public List<object> UploadToQiniu()
        {
            var list = new List<object>();

            var mac = new Mac(_Qny.qiniuyunAK, _Qny.qiniuyunSK);

            var putPolicy = new PutPolicy
            {
                Scope = _Qny.qiniuyunBucket
            };

            var uploadToken = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());

            var config = new Config()
            {
                Zone = Zone.ZONE_CN_East,
                UseHttps = true
            };
            var formUploader = new FormUploader(config);

            var files = Request.Form.Files;
            foreach (var file in files)//获取多个文件列表集合
            {
                if (file.Length > 0)
                {
                    var fileName = ContentDispositionHeaderValue
                                    .Parse(file.ContentDisposition)
                                    .FileName
                                    .Trim('"');
                    var qiniuName = _Qny.prefixPath + "/" + DateTime.Now.ToString("yyyyMMddHHmmssffffff") + fileName;//重命名文件加上时间戳

                    var stream = file.OpenReadStream();
                    var result = formUploader.UploadStream(stream, qiniuName, uploadToken, null);

                    if (result.Code == 200)
                    {
                        list.Add(new { fileName, qiniuName, uploadTime = DateTime.Now });
                    }
                    else
                    {
                        throw new Exception(result.RefText);//上传失败错误信息
                    }
                }
            }

            return list;
        }

        public IActionResult FileList()
        {
            return View();
        }

        public IActionResult DownloadFromQiniu()
        {
            //var mac = new Mac(_Qny.qiniuyunAK, _Qny.qiniuyunSK);
            //var domain = "http://81l6j0.s3-cn-east-1.qiniucs.com";
            //var fileName = "Hummingbird_by_Shu_Le.jpg";

            //var accessUrl = DownloadManager.CreatePrivateUrl(mac, domain, fileName);

            //var saveFile = "/saved-1.jpg";
            //var result = DownloadManager.Download(accessUrl, saveFile);

            //var domain = "http://81l6j0.s3-cn-east-1.qiniucs.com/";
            //var fileName = "Hummingbird_by_Shu_Le.jpg";
            //var result = DownloadManager.CreatePublishUrl(domain, fileName);

            //var rawUrl = "http://81l6j0.s3-cn-east-1.qiniucs.com/Hummingbird_by_Shu_Le.jpg";
            //var saveFile = "C:\\QFL\\saved-snow.jpg";
            //var result = DownloadManager.Download(rawUrl, saveFile);

            return View();
        }
    }
}
